<?php
/**
 * Created by PhpStorm.
 * User: Dean.Wu
 * Date: 2018/1/22 0022
 * Time: 20:50
 */
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\TagPost;
use App\Models\Types;
use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class PostController extends Controller{

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 创建
     * @author wudean
     */
    public function Create(){
        return view('web.post.create');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @name 存贮数据
     * @author wudean
     */
    public function store(Request $request){
        //验证
        $this->validate($request,[
            'title' => 'required|max:225|min:4',
            'content' => 'required | min:100',
        ]);
        //逻辑
        $user_id=\Auth::id();
        $params = array_merge(request(['title', 'content']),compact('user_id'));
        Post::create($params);
        //跳转
        return redirect('/');
    }

    /**
     * @param Request $request
     * @return bool
     * @name 文件上传
     */
    public function ImageUpload(Request $request){
        //获取文件
        $file = $request->file('wangEditorH5File');
        //处理文件
        $ext=$file->getClientOriginalExtension();
        $fileName='iunan/'.date('YmdHis').'_'.uniqid().'.'.$ext;
        //上传介质
        $upManager=new UploadManager();
        $auth = new Auth($_ENV['ACCESSKEY'], $_ENV['SECRETKEY']);
        $token = $auth->uploadToken($_ENV['BUCKET']);
        list($ret, $error) = $upManager->putFile($token, $fileName,$file->getRealPath());
        $file_name=$_ENV['QINIU_HOST'].$fileName;

        return $file_name;
    }
    /**
     * @param Post $post
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 详情页面
     * @author wudean
     */
    public function show(Post $post){
        //访问量增加
        Post::PostUpHandle($post->id);
        //标签
        $tags=TagPost::getListByUserIdArrayAll($post->id);
        //分类名称
        $type_info=Types::getInfoById($post->type_id);
        //推荐数据
        $re_lists=$this->getRecommendListPost($post);
        $post->type_name=$type_info->name;
        return view('home.index.show',compact('post','tags','re_lists'));
    }

    /**
     * @param $post
     * @return mixed
     * @author Deann.wu
     * @name 获取推荐数据
     */
    public function getRecommendListPost($post){
        return Post::getReList($post);
    }


}